package org.jproggy.pagesally;

import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class GeneratorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Generator gen;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String uri = req.getRequestURI();
		if (!uri.endsWith(".html")) uri += "index.html";
		if (gen.hasPage(uri)) {
			gen.generateSingleFile(uri, resp.getWriter());
		} else {
			URLConnection connection = getServletContext().getResource(getPath(req)).openConnection();
			resp.setContentType(connection.getContentType());
			IOUtils.copy(connection.getInputStream(), resp.getOutputStream());
		}
	}

	private String getPath(HttpServletRequest req) {
		String path = req.getRequestURI() ;
		if (path == null) return "/";
		return "/" + path;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	public void init() throws ServletException {
		try {
			gen = new Generator(getBaseDir(), new File(getServletContext().getRealPath("/")), getLocale());
		} catch (IOException e) {
			throw new ServletException(e);
		}
	}

	private File getBaseDir() {
		return new File(getInitParameter("baseDir"));
	}

	private Locale getLocale() {
		String lang = getInitParameter("locale");
		if (lang == null)  return Locale.getDefault();
		return new Locale(lang);
	}

}
